<template> 
  <div class="app-container">
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>数据列表</span>
      <el-button type="primary" size="mini" class="btn-add" @click="handleAdd()" style="margin-left: 20px;float: right;padding: 10px 40px;">添加</el-button>
    </el-card>
    <div class="table-container">
      <el-table ref="adminTable"
                :data="list"
                style="width: 100%;"
                v-loading="listLoading" border>
        <el-table-column label="编号" width="100" align="center">
          <template slot-scope="scope">{{ scope.row.id }}</template>
        </el-table-column>
        <el-table-column label="登录账号" align="center">
          <template slot-scope="scope">{{ scope.row.admin_username }}</template>
        </el-table-column>
        <el-table-column label="姓名" align="center">
          <template slot-scope="scope">{{ scope.row.admin_fullname }}</template>
        </el-table-column>
        <el-table-column label="邮箱" align="center">
          <template slot-scope="scope">{{ scope.row.admin_email }}</template>
        </el-table-column>
        <el-table-column label="电话号码" align="center">
          <template slot-scope="scope">{{ scope.row.admin_phone }}</template>
        </el-table-column>
        <el-table-column label="添加时间" align="center">
          <template slot-scope="scope">{{ scope.row.admin_createTime | formatDateTime }}</template>
        </el-table-column>
        <el-table-column label="最后登录" align="center">
          <template slot-scope="scope">{{ scope.row.admin_loginTime | formatDateTime }}</template>
        </el-table-column>
        <el-table-column label="是否启用" align="center">
          <template slot-scope="scope">
            <el-switch
              @change="handleStatusChange(scope.$index, scope.row)"
              :active-value="1"
              :inactive-value="0"
              v-model="scope.row.admin_status">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button size="mini"
                       type="text"
                       @click="handleSelectRole(scope.$index, scope.row)">分配角色
            </el-button>
            <el-button size="mini"
                       type="text"
                       @click="handleUpdate(scope.$index, scope.row)">
              编辑
            </el-button>
            <el-button size="mini"
                       type="text"
                       @click="handleDelete(scope.$index, scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container" style="text-align: center;margin-top: 20px">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :current-page.sync="listQuery.page"
        :page-size="listQuery.page_size"
        :page-sizes="[10,15,20]"
        :total="total">
      </el-pagination>
    </div>
    <el-dialog
      :title="isEdit?'编辑用户':'添加用户'"
      :visible.sync="dialogVisible"
      width="40%">
      <el-form :model="admin"
               :rules="rules"
               ref="adminForm"
               label-width="150px" size="small">
        <el-form-item label="登录账号：" prop="admin_username">
          <el-input v-model="admin.admin_username" style="width: 250px" placeholder="请输入登录账号"></el-input>
        </el-form-item>
        <el-form-item label="登录密码：" prop="admin_password">
          <el-input v-model="admin.admin_password" type="password" style="width: 250px"
                    placeholder="请输入登录密码"></el-input>
        </el-form-item>
        <el-form-item label="显示姓名：" prop="admin_fullname">
          <el-input v-model="admin.admin_fullname" style="width: 250px" placeholder="请输入显示姓名"></el-input>
        </el-form-item>
        <el-form-item label="电话号码：" prop="admin_phone">
          <el-input v-model.number="admin.admin_phone" style="width: 250px" placeholder="请输入电话号码"></el-input>
        </el-form-item>
        <el-form-item label="分配角色：" prop="group_ids">
          <el-select @change="$forceUpdate()" v-model="admin.group_ids" style="width: 250px" multiple placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.group_title"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          prop="admin_email"
          label="邮箱地址："
          :rules="[
      { required: true, message: '请输入邮箱地址', trigger: 'blur' },
      { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
    ]"
        >
          <el-input v-model="admin.admin_email" style="width: 250px" placeholder="请输入邮箱地址"></el-input>
        </el-form-item>
        <el-form-item label="是否启用：" prop="admin_status">
          <el-radio-group v-model="admin.admin_status">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="handleDialogConfirm('adminForm')" size="small">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="分配角色："
      :visible.sync="allocDialogVisible"
      width="30%">
      <el-select @change="$forceUpdate()" v-model="admin.group_ids" size="small" style="width: 80%" multiple
                 placeholder="请选择角色">
        <el-option
          v-for="item in roleList"
          :key="item.id"
          :label="item.group_title"
          :value="item.id">
        </el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="allocDialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="handleAllocDialogConfirm()" size="small">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  adminAdd, adminList, adminAjax, adminInfo, adminEdit, adminDel, adminAuthEdit
} from '@/api/login';
import {fetchAllRoleList, groupLine, groupList} from '@/api/role';
import {formatDate} from '@/utils/date';
import {isvalidPhone} from '@/utils/validate';

const defaultListQuery = {
  page: 1,
  page_size: 10
};
const defaultAdmin = {
  admin_username: null,
  admin_fullname: null,
  admin_phone: null,
  admin_email: null,
  admin_password: null,
  admin_status: null,
  group_ids: null
};
export default {
  name: 'adminList',
  data() {
    let validPhone = (rule, value, callback) => {
      if ( !value ) {
        callback(new Error('请输入电话号码'))
      } else if ( !isvalidPhone(value) ) {
        callback(new Error('请输入正确的11位手机号码'))
      } else {
        callback()
      }
    }

    return {
      value1: [],
      id: "",
      listQuery: Object.assign({}, defaultListQuery),
      list: null,
      total: null,
      listLoading: false,
      dialogVisible: false,
      admin: Object.assign({}, defaultAdmin),
      isEdit: false,
      allocDialogVisible: false,
      allocRoleIds: [],
      allRoleList: [],
      allocAdminId: null,
      rules: {
        admin_username: [
          {required: true, message: '请输入登录账号', trigger: 'blur'}
        ],
        admin_password: [
          {required: true, message: '请输入登录密码', trigger: 'blur'}
        ],
        admin_fullname: [
          {required: true, message: '请输入显示姓名', trigger: 'blur'}
        ],
        admin_status: [
          {required: true, message: '请选择是否启用', trigger: 'change'}
        ], admin_phone: [
          {required: true, trigger: 'blur', validator: validPhone}
        ], group_ids: [
          {required: true, message: '请选择角色', trigger: 'change'}
        ]
      },
      roleList: []
    }
  },
  created() {
    this.getList();
    this.getRoleList();
    /*  this.getAllRoleList();*/
  },
  filters: {
    formatDateTime(time) {
      if ( time == null || time === '' ) {
        return 'N/A';
      }
      let date = new Date(time);
      return formatDate(date, 'yyyy-MM-dd')
    }
  },
  methods: {
    /**
     * 获取角色列表数据
     */
    getRoleList() {
      this.listLoading = true;
      groupList(this.listQuery).then(response => {
        this.listLoading = false;
        console.log(response);
        this.roleList = response.data.data_list
      });
    },

    /**
     * 列表数据
     */
    getList() {
      this.listLoading = true;
      adminList(this.listQuery).then(response => {
        this.listLoading = false;
        console.log(response);
        this.list = response.data.data_list;
        this.total = response.data.total;
      });
    },
    /* handleResetSearch() {
       this.listQuery = Object.assign({}, defaultListQuery);
     },*/
    /* handleSearchList() {
       this.listQuery.pageNum = 1;
       this.getList();
     },*/
    handleSizeChange(val) {
      this.listQuery.page_size = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    },
    handleAdd() {
      this.dialogVisible = true;
      this.isEdit = false;
      this.admin = Object.assign({}, defaultAdmin);
    },
    /**
     * 修改列表状态
     * @param index
     * @param row
     */
    handleStatusChange(index, row) {
      this.$confirm('是否要修改该状态?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        adminAjax(row.id).then(response => {
          this.$message({
            type: 'success',
            message: '修改成功!'
          });
        }).catch(e=>{
          console.log(e);});
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消修改'
        });
        this.getList();
      })
    },
    /**
     * 删除
     * @param index
     * @param row
     */
    handleDelete(index, row) {
      this.$confirm('是否要删除该用户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        adminDel(row.id).then(response => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getList();
        });
      }).catch(e => e);
    },
    /**
     * 获取列表单条信息
     * @param index
     * @param row
     */
    handleUpdate(index, row) {
      console.log(row)
      this.id = row.id;
      this.dialogVisible = true;
      this.isEdit = true;
      this.listLoading = true;
      adminInfo(row.id).then(response => {
        this.listLoading = false;
        console.log(response);
        this.admin = response.data
        let data = response.data.group_ids
        var arrIntCzfaIds = []
        for ( var arrInt in data ) {
          arrIntCzfaIds.push(parseInt(data[ arrInt ]))
        }
        this.admin.group_ids = arrIntCzfaIds
      });
    },
    /**
     * 新增/修改
     * @param formName
     */
    handleDialogConfirm(formName) {
      this.$refs[ formName ].validate((valid) => {
        if ( valid ) {
          this.$confirm('是否要确认?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            if ( this.isEdit ) {
              adminEdit(Object.assign({id: this.id}, this.admin)).then(response => {
                this.$message({
                  message: '修改成功！',
                  type: 'success'
                });
                this.dialogVisible = false;
                this.getList();
              })
            } else {
              adminAdd(this.admin).then(response => {
                this.$message({
                  message: '添加成功！',
                  type: 'success'
                });
                this.dialogVisible = false;
                this.getList();
              })
            }
          })
        }
      });
    },
    /**
     * 分配角色
     */
    handleAllocDialogConfirm() {
      this.$confirm('是否要确认?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        adminAuthEdit({id: this.allocAdminId, group_ids: this.admin.group_ids}).then(response => {
          this.$message({
            message: '分配成功！',
            type: 'success'
          });
          this.allocDialogVisible = false;
        })
      })
    },
    handleSelectRole(index, row) {
      this.allocAdminId = row.id;
      this.allocDialogVisible = true;
      /*      this.getRoleListByAdmin(row.id);*/
    },
    getAllRoleList() {
      fetchAllRoleList().then(response => {
        this.allRoleList = response.data;
      });
    },
    getRoleListByAdmin(adminId) {
      getRoleByAdmin(adminId).then(response => {
        let allocRoleList = response.data;
        this.allocRoleIds = [];
        if ( allocRoleList != null && allocRoleList.length > 0 ) {
          for ( let i = 0; i < allocRoleList.length; i++ ) {
            this.allocRoleIds.push(allocRoleList[ i ].id);
          }
        }
      });
    }
  }
}
</script>
<style></style>


